package com.wjm.thread.test0;

public class MyRunnable implements Runnable {
    private int ticketCount = 50;// 总的票数，这个是共享资源，多个线程都会访问
    Object mutex = new Object();// 锁，自己定义的，或者使用实例的锁

    @Override
    public void run() {

        sellTicket();

        System.out.println("run..." + Thread.currentThread().getId() + ":" + Thread.currentThread().getName() + "票已经卖完！");
    }

    private void sellTicket() {
        synchronized (mutex) {// 当操作的是共享数据时,
            while (ticketCount > 0) {// 循环是指线程不停的去卖票
                synchronized (mutex) {// 当操作的是共享数据时,
                    System.out.println("run..." + Thread.currentThread().getId() + ":" + Thread.currentThread().getName() + "正在卖票,还剩" + ticketCount-- + "张票");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
